import Vue from "vue";
import Vuex from "vuex";
import dynamicRoutes from '@/router/dynamicRoutes'
import allRoutes from '@/router/allRoutes'
import recursionRoutes from '@/utils/recursionRoutes'
import * as api from "@/api"
import router from "../router"
Vue.use(Vuex);
// 刷新页面信息丢失是因为刷新后会重新执行vuex逻辑
// 如何进行调试
let buttons = localStorage.getItem("userButtons") || "{}"
export default new Vuex.Store({
    state: {
        sideMenu: [], //用户侧边栏菜单
        menuCollapse: false,
        crumbs: [],
        userBtns: JSON.parse(buttons) //用户按钮
    },
    mutations: {
        // 更改state唯一方式
        SET_SIDE_MENU(state, payload) {
            state.sideMenu = [...payload]
                // 设置dynamicRoutes=>将用户路由添加到数组中的path="/"的对象children中
                // 添加完后还要将dynamicRoutes添加到系统路由中去
                // 将dynamicRoutes动态添加到路由
            let target = dynamicRoutes.find(item => item.path === "/");
            target.children = [...payload]
            router.addRoutes(dynamicRoutes)
        },
        // 设置菜单收起展开
        SET_MENU_COLLAPSE(state) {
            state.menuCollapse = !state.menuCollapse
        },
        // 设置面包屑
        SET_CRUMBS(state, payload) {
            state.crumbs = payload
        },
        // 设置用户的按钮权限
        SET_USER_BTNS(state, payload) {
            state.userBtns = payload
        }
    },
    actions: {
        // 异步请求
        // 获取用户菜单
        GET_MENU_LIST({ commit }) {
            return api.getMenuListApi()
                .then(res => {
                    // console.log(res);
                    let menuList = res.data.menuList
                        // console.log(menuList);
                    let userMenu = recursionRoutes(allRoutes, menuList)
                    commit("SET_SIDE_MENU", userMenu)
                })
        }
    },
    modules: {},
});